package cn.iocoder.yudao.module.iot.util;


import cn.iocoder.yudao.module.iot.vo.ApiQueryResponse;
import cn.iocoder.yudao.module.iot.vo.ProductInfoVo;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.iot20180120.*;
import com.aliyun.sdk.service.iot20180120.models.*;
import com.aliyuncs.utils.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * desc:阿里云api接口工具类
 * @author:fuzhifei
 * @date:2023/12/18 18:31

 */

public class AliyunIotApiUtil {


    @Value("${iot.IotInstanceId}")
    private String IotInstanceId;

    @Value("${iot_api.IotApiAccessKeyId}")
    private String IotApiAccessKeyId;

    @Value("${iot_api.IotAccessKeySecret}")
    private String IotAccessKeySecret;

    private final static Logger logger = LoggerFactory.getLogger(AliyunIotApiUtil.class);



    /**
     * desc:批量查询产品列表
     * @author:fuzhifei
     * @date:2023/12/5 18:57
     * @param currentPage 当前页
     * @param pageSize 每页查询的数据
     * @return List<ProductInfoVo> 返回产品列表集合
     */

    public static Object getProductInfoList(int currentPage, int pageSize) {
        AsyncClient client = getAsyncClient();

        QueryProductListRequest queryProductListRequest = QueryProductListRequest.builder()
                .iotInstanceId("iot-010a7d09")
                .pageSize(pageSize)
                .currentPage(currentPage)
                .build();
        CompletableFuture<QueryProductListResponse> response = client.queryProductList(queryProductListRequest);
        // Synchronously get the return value of the API request
        QueryProductListResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        resp.getBody().getData();
        String resultJson = new Gson().toJson(resp.getBody().getData());
        logger.info("获取产品列表云端返回的结果是："+resultJson);
        client.close();
        return resp.getBody().getData();
    }


    public static Object getProductInfo(String productKey) {
        AsyncClient client = getAsyncClient();

        QueryProductRequest queryProductRequest = QueryProductRequest.builder()
                .iotInstanceId("iot-010a7d09")
                .productKey(productKey)
                .build();
        CompletableFuture<QueryProductResponse> queryProduct = client.queryProduct(queryProductRequest);
        // Synchronously get the return value of the API request
        QueryProductResponse resp = null;
        try {
            resp = queryProduct.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        String resultJson = new Gson().toJson(resp.getBody().getData());
        logger.info("获取产品详情的结果是："+resultJson);
        client.close();
        return resp.getBody().getData();
    }


    public static Object getDeviceListByProductKey(String productKey,int currentPage,int pageSize,String nextToken) {
        AsyncClient client = getAsyncClient();
        QueryDeviceRequest queryDeviceRequest=null;
        if(StringUtils.isEmpty(nextToken)){
            queryDeviceRequest = QueryDeviceRequest.builder()
                    .iotInstanceId("iot-010a7d09")
                    .productKey(productKey)
                    .pageSize(pageSize)
                    .currentPage(currentPage)
                    .build();
        }else{
            queryDeviceRequest = QueryDeviceRequest.builder()
                    .iotInstanceId("iot-010a7d09")
                    .productKey(productKey)
                    .pageSize(pageSize)
                    .currentPage(currentPage)
                    .nextToken(nextToken)
                    .build();
        }

        CompletableFuture<QueryDeviceResponse> queryDevice = client.queryDevice(queryDeviceRequest);
        QueryDeviceResponse resp = null;
        try {
            resp = queryDevice.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        String resultJson = new Gson().toJson(resp.getBody());
        logger.info("获取设备列表的结果是："+resultJson);
        client.close();
        return resp.getBody();
    }


    public static String getDevicestatus(String productKey,String deviceName) {
        AsyncClient client = getAsyncClient();
        GetDeviceStatusRequest getDeviceStatusRequest = GetDeviceStatusRequest.builder()
                .iotInstanceId("iot-010a7d09")
                .productKey(productKey)
                .deviceName(deviceName)
                .build();
        CompletableFuture<GetDeviceStatusResponse> deviceStatus = client.getDeviceStatus(getDeviceStatusRequest);
        GetDeviceStatusResponse resp = null;
        try {
            resp = deviceStatus.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        String resultJson = new Gson().toJson(resp.getBody());
        logger.info("getDevicestatus结果是："+resultJson);
        client.close();
        return resultJson;
    }



    public static String batchGetDeviceStatus(String productKey,List<String> deviceNameList) {
        AsyncClient client = getAsyncClient();
        BatchGetDeviceStateRequest batchGetDeviceStateRequest = BatchGetDeviceStateRequest.builder()
                .iotInstanceId("iot-010a7d09")
                .productKey(productKey)
                .deviceName(deviceNameList)
                .build();
        CompletableFuture<BatchGetDeviceStateResponse> batchGetDeviceState = client.batchGetDeviceState(batchGetDeviceStateRequest);
        BatchGetDeviceStateResponse resp = null;
        try {
            resp = batchGetDeviceState.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        String resultJson = new Gson().toJson(resp.getBody());
        logger.info("batchGetDeviceState结果是："+resultJson);
        client.close();
        return resultJson;
    }


    public static Object queryDeviceByStatus(Integer status,String productKey,int currentPage,int pageSize) {
        AsyncClient client = getAsyncClient();
        QueryDeviceByStatusRequest byStatusRequest = QueryDeviceByStatusRequest.builder()
                .iotInstanceId("iot-010a7d09")
                .productKey(productKey)
                .status(status)
                .currentPage(currentPage)
                .pageSize(pageSize)
                .build();
        CompletableFuture<QueryDeviceByStatusResponse> queryDeviceByStatus = client.queryDeviceByStatus(byStatusRequest);
        QueryDeviceByStatusResponse resp = null;
        try {
            resp = queryDeviceByStatus.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        String resultJson = new Gson().toJson(resp.getBody());
        logger.info("queryDeviceByStatus结果是："+resultJson);
        client.close();
        return resp.getBody();
    }


    public static Object queryDeviceStatistics(String productKey) {
        AsyncClient client = getAsyncClient();
        QueryDeviceStatisticsRequest deviceStatisticsRequest=null;
        if(StringUtils.isEmpty(productKey)){
            deviceStatisticsRequest = QueryDeviceStatisticsRequest.builder()
                    .iotInstanceId("iot-010a7d09")
                    .build();
        }else{
            deviceStatisticsRequest = QueryDeviceStatisticsRequest.builder()
                    .iotInstanceId("iot-010a7d09")
                    .productKey(productKey)
                    .build();
        }

        CompletableFuture<QueryDeviceStatisticsResponse> statistics = client.queryDeviceStatistics(deviceStatisticsRequest);
        QueryDeviceStatisticsResponse resp = null;
        try {
            resp = statistics.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        String resultJson = new Gson().toJson(resp.getBody());
        logger.info("queryDeviceStatistics结果是："+resultJson);
        client.close();
        return resp.getBody();
    }


    public static Object queryDeviceDetail(String productKey,String deviceName) {
        AsyncClient client = getAsyncClient();
        QueryDeviceDetailRequest queryDeviceDetailRequest = QueryDeviceDetailRequest.builder()
                .iotInstanceId("iot-010a7d09")
                .productKey(productKey)
                .deviceName(deviceName)
                .build();
        CompletableFuture<QueryDeviceDetailResponse> deviceDetail = client.queryDeviceDetail(queryDeviceDetailRequest);
        QueryDeviceDetailResponse resp = null;
        try {
            resp = deviceDetail.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        String resultJson = new Gson().toJson(resp.getBody());
        logger.info("queryDeviceDetail结果是："+resultJson);
        client.close();
        return resp.getBody();
    }


    private static AsyncClient getAsyncClient() {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId("LTAI5t97w1xqTfGs133RnQpb")
                .accessKeySecret("sZ2la7x1aPRPEKMqG2sipfcPsRAwGu")
                .build());
        AsyncClient client = AsyncClient.builder()
                .region("cn-beijing") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("iot.cn-beijing.aliyuncs.com")
                )
                .build();
        return client;
    }

    public static void main(String[] args) {
        /*String productInfoList = getProductInfoList(1, 5);
        System.out.println(productInfoList);*/
        /*String productInfo = getProductInfo("k0aivZRsAgr");
        System.out.println(productInfo);*/
        /*String deviceList = getDeviceListByProductKey("k0aivZRsAgr",1,10);
        System.out.println(deviceList);*/
        String deviceStatus = getDevicestatus("k0aivZRsAgr","898604F2102320850299");
        System.out.println(deviceStatus);
    }



}
